/*
   Copyright 2011 marcopar@gmail.com

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/

package eu.flatworld.worldexplorer.gui.options;

import eu.flatworld.commons.log.LogX;
import eu.flatworld.worldexplorer.WorldExplorer;
import eu.flatworld.worldexplorer.Config;
import eu.flatworld.worldexplorer.gui.MainFrame;
import eu.flatworld.commons.Storage;
import java.awt.Color;
import java.awt.Component;
import java.awt.Toolkit;
import java.io.File;
import java.util.logging.Level;
import javax.swing.ImageIcon;

public class CacheAndDataOption extends javax.swing.JPanel implements OptionProvider {

    public CacheAndDataOption() {
        initComponents();
        jLabel3.setVisible(false);
        jtfCacheSize.setVisible(false);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents
    private void initComponents() {
        jLabel1 = new javax.swing.JLabel();
        jtfCache = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        jtfData = new javax.swing.JTextField();
        jbReset = new javax.swing.JButton();
        jLabel3 = new javax.swing.JLabel();
        jtfCacheSize = new javax.swing.JTextField();

        jLabel1.setText("Cache path:");
        jLabel1.setToolTipText("Where temporary files are stored.");

        jtfCache.setToolTipText("Where temporary files are stored.");

        jLabel2.setText("Data path:");
        jLabel2.setToolTipText("Where data packs are stored. This data will never be deleted.");

        jtfData.setToolTipText("Where data packs are stored. This data will never be deleted.");

        jbReset.setText("Reset");
        jbReset.setMargin(new java.awt.Insets(1, 2, 1, 1));
        jbReset.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbResetActionPerformed(evt);
            }
        });

        jLabel3.setText("Cache size:");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel3)
                            .addComponent(jLabel1))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jtfCacheSize, javax.swing.GroupLayout.DEFAULT_SIZE, 152, Short.MAX_VALUE)
                            .addComponent(jtfCache, javax.swing.GroupLayout.DEFAULT_SIZE, 152, Short.MAX_VALUE)))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGap(20, 20, 20)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel2)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jtfData, javax.swing.GroupLayout.DEFAULT_SIZE, 152, Short.MAX_VALUE))
                            .addComponent(jbReset, javax.swing.GroupLayout.Alignment.TRAILING))))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jtfCache, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(jtfCacheSize, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(jtfData, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jbReset)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents
    private void jbResetActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbResetActionPerformed
        jtfData.setText(WorldExplorer.OPTIONS_DEFAULT_DATAPATH);
        jtfCache.setText(WorldExplorer.OPTIONS_DEFAULT_CACHEPATH);
    }//GEN-LAST:event_jbResetActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JButton jbReset;
    private javax.swing.JTextField jtfCache;
    private javax.swing.JTextField jtfCacheSize;
    private javax.swing.JTextField jtfData;
    // End of variables declaration//GEN-END:variables
    @Override
    public boolean valid() {
        boolean error = false;
        boolean globalValid = true;
        String data = jtfData.getText();
        if (data == null || data.equals("")) {
            error = false;
        } else {
            File f = new File(data);
            if (!f.exists() || !f.isDirectory()) {
                error = true;
            }
        }
        if (error) {
            jtfData.setBackground(Color.ORANGE);
            globalValid = false;
        } else {
            jtfData.setBackground(java.awt.SystemColor.text);
        }

        error = false;
        String cache = jtfCache.getText();
        if (error) {
            jtfCache.setBackground(Color.ORANGE);
            globalValid = false;
        } else {
            jtfCache.setBackground(java.awt.SystemColor.text);
        }

        error = false;
        int cacheSize = 0;
        try {
            cacheSize = Integer.parseInt(jtfCacheSize.getText());
        } catch (Exception ex) {
            error = true;
        }
        if (error) {
            jtfCacheSize.setBackground(Color.ORANGE);
            globalValid = false;
        } else {
            jtfCacheSize.setBackground(java.awt.SystemColor.text);
        }
        return globalValid;
    }

    boolean checkChange() {
        if (!jtfData.getText().equals(Config.getConfig().getDataPath())) {
            return true;
        }
        if (!jtfCache.getText().equals(Config.getConfig().getCachePath())) {
            return true;
        }
        return false;
    }

    @Override
    public void load() {
        jtfData.setText(Config.getConfig().getDataPath());
        jtfCache.setText(Config.getConfig().getCachePath());
        jtfCacheSize.setText("" + Config.getConfig().getCacheSize());
    }

    @Override
    public void store() {
        boolean changed = checkChange();
        Config.getConfig().setDataPath(jtfData.getText());
        Config.getConfig().setCachePath(jtfCache.getText());
        Config.getConfig().setCacheSize(Integer.parseInt(jtfCacheSize.getText()));
        try {
            Config.getConfig().store();
        } catch (Exception ex) {
            LogX.log(Level.WARNING, "Error saving preferences", ex, true);
        }

        if (changed) {
            ((MainFrame) Storage.getStorage().get(MainFrame.class.getName())).reinitLayers();
        }
    }

    @Override
    public ImageIcon getIcon() {
        return new ImageIcon(Toolkit.getDefaultToolkit().getImage(getClass().getResource("/eu/flatworld/worldexplorer/gui/options/folder-16.png")));
    }

    @Override
    public Component getComponent() {
        return this;
    }

    @Override
    public String getTitle() {
        return "Cache & Data";
    }

    @Override
    public String getTooltip() {
        return null;
    }
}
